<template>
  <el-dialog
    title="成员变量注入"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    append-to-body
  >
    <el-form ref="form" :model="form" size="mini">
       <el-table :data="form.records" border>

        <el-table-column label="名称" prop="name">
          <template v-slot="scope">
            <el-input v-model="scope.row.name"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="类型" prop="type">
          <template v-slot="scope">
            <el-select
            v-model="scope.row.type"
            placeholder="请选择类型"
            clearable
            filterable
          >
            <el-option
              v-for="(item, index) in fieldTypes"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
          </template>
        </el-table-column>

        <el-table-column label="值" prop="value">
          <template v-slot="scope">
            <el-input v-model="scope.row.value"></el-input>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <template v-slot="scope">
            <el-form-item>
              <el-button type="danger" icon="el-icon-minus" circle @click="remove(scope.$index)" />
            </el-form-item>
          </template>
        </el-table-column>
      </el-table> 
    </el-form>
    <span slot="footer">
      <el-button type="info" @click="close">取消</el-button>
      <el-button type="primary" @click="add">新增</el-button>
      <el-button type="success" @click="save">确定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { FIELD_TYPES } from './constants'

export default {
  name: 'Field',
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      fieldTypes: FIELD_TYPES,
      visible: true,

      form: {
        records: this.value
      }
    }
  },
  methods: {
    save() {
      this.$refs['form'].validate().then(() => {
        this.$emit('save-fields', this.form.records)
        this.close()
      }).catch(e => console.error(e))
    },
    add() {
      this.form.records.push({
        type: 'string'
      })
    },

    close() {
      this.visible = false
      this.$emit('close')
    },
    remove(index) {
      this.form.records.splice(index, 1)
    }
  }
}
</script>
